﻿using CefSharp;
using CefSharp.WinForms;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace CefSharpDemo
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        ChromiumWebBrowser browser;
        public MainWindow()
        {
            InitializeComponent();
            this.Loaded += MainWindow_Loaded;
        }

        /// <summary>
        /// 初始化，注册js(googleBrowser约定名称)
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            this.txtUrl.Text = "http://127.0.0.1:33322/index.html";
            browser = new CefSharp.WinForms.ChromiumWebBrowser("http://127.0.0.1:33322/index.html");
            webHost.Child = browser;
            browser.RegisterJsObject("googleBrowser", new _Event(), new BindingOptions() { CamelCaseJavascriptNames = false });
        }

        /// <summary>
        /// 调用JS方法
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            Task<CefSharp.JavascriptResponse> t = browser.EvaluateScriptAsync("test", this.txtMessage.Text);
            t.Wait();
            if (t.Result.Result != null)
            {
                this.txtResult.Text += t.Result.Result.ToString() + "\n";
            }
        }

        /// <summary>
        /// 新URL
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnGo_Click(object sender, RoutedEventArgs e)
        {
            browser.GetMainFrame().LoadUrl(this.txtUrl.Text);
        }
    }
    public class _Event
    {
        /// <summary>
        /// 供Js调用本地方法
        /// </summary>
        /// <param name="userName"></param>
        /// <returns></returns>
        public string getName(string userName)
        {
            return "客户端处理后：" + userName;
        }
    }
}
